package com.intellif.mozping.waitandnotify;

/**
 * @author by mozping
 * @Classname Shop
 * @Description 商店实体类
 * @Date 2019/4/25 20:18
 */
public class Shop {

    //商店里面的玩具
    private String toy;

    public Shop(String toy) {
        this.toy = toy;
    }

    //等待玩具，如果没有玩具就阻塞，一旦有玩具了，会唤醒等待玩具的线程
    public synchronized void waitToy(long mills) {
        long begin = System.currentTimeMillis();
        long remain = mills;
        long end = System.currentTimeMillis() + mills;
        while ("nothing".equalsIgnoreCase(toy) && remain > 0) {
            try {
                wait(remain);
                remain = end - System.currentTimeMillis();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if ("nothing".equalsIgnoreCase(toy)) {
            System.out.println(Thread.currentThread().getName() + "线程不等待了，等待了"
                    + (System.currentTimeMillis() - begin) + " ms 了...");
        } else {
            System.out.println(Thread.currentThread().getName() + "收到了通知，有玩具 " + toy + " 了...");
        }

    }

    //玩具到货了，玩具到货之后通知等待玩具的线程
    public synchronized void sendToy(String toy) {
        this.toy = toy;
        System.out.println("玩具到货了...");
        notifyAll();
    }
}
